package com.dyp.rabbitmqdemo.res;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

@RestController
@RequestMapping(value = "/api")
public class TestRes {


    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/simple/mq")
    public void hello() {
       rabbitTemplate.convertAndSend("simple","hello springboot rabbitmq");
    }

    @GetMapping("/worker/mq")
    public void worker() {
        for(int i = 0; i < 10; i++){
            rabbitTemplate.convertAndSend("worker","worker model " + i);
        }
    }

    @GetMapping("/fanout/mq")
    public void fanout() {
            rabbitTemplate.convertAndSend("fanout","","fanout model " );
    }

    @GetMapping("/routing/mq")
    public void routing() {
        rabbitTemplate.convertAndSend("routing","info","routing model " );
    }

    @GetMapping("/topic/mq")
    public void topics() {
        rabbitTemplate.convertAndSend("topic","user.oerder","topic model " );
    }

    @GetMapping("/test/mq")
    public void testMq() {
        for(int i = 0; i<1000;i++){
            System.out.println(i);
            rabbitTemplate.convertAndSend("simple" + i,"hello springboot rabbitmq"+ i);
        }
    }

    @GetMapping("/manul/mq/{queueName}")
    public String manulRecieveInfo(@PathVariable(value = "queueName") String queueName) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.1.3");
        factory.setPort(5672);
        factory.setUsername("dyp");
        factory.setPassword("123456");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //参数1：队列名称 如果不存在自动创建  参数2：队列是否持久化  参数3：是否独占队列  参数4：消息传输完成是否自动删除
        channel.queueDeclare(queueName,false,false,false,null);

        DeliverCallback deliverCallback = (consumerTag, delivery) ->{
            String message = new String(delivery.getBody(),"UTF-8");
            System.out.println("Received :"+message);
        };
        channel.basicConsume(queueName,true,deliverCallback, consumerTag->{});

        return "message";
    }
}
